package com.example.choupaiapp.main.activity.mine;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.bean.EnergyTaskBean;
import com.example.choupaiapp.main.bean.MineEnergyList;
import com.example.choupaiapp.main.constant.Url;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/20.
 */

public class MineEnergyActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.rule)
    TextView rule;
    @BindView(R.id.enery)
    TextView enery;
    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private QuickAdapter<MineEnergyList.PageBean.ListBean> quickAdapter;
    private EnergyTaskBean mEnergyTaskBean;
    private int pageNum = 1;
    private int pageSize = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_energy);
    }

    @Override
    protected void initView() {
        setTitle("我的能量");
        right_tv.setText("更多任务");

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        quickAdapter = new QuickAdapter<MineEnergyList.PageBean.ListBean>(context, R.layout.item_enery_detail) {
            @Override
            protected void convert(BaseAdapterHelper helper, MineEnergyList.PageBean.ListBean item) {
                ImageView img = helper.getView(R.id.img);
                TextView task = helper.getView(R.id.task);
                TextView energy = helper.getView(R.id.energy);
                ImageView quicken_times = helper.getView(R.id.quicken_times);
                helper.setText(R.id.time, item.getApplyTime());

                if (item.getProvider().equals("conversion")) {
                    energy.setText("" + item.getNumber());
                } else {
                    energy.setText("+" + item.getNumber());
                }

                if (item.getMultiple() != null) {
                    if (item.getMultiple().intValue() == 2) {
                        quicken_times.setVisibility(View.VISIBLE);
                        quicken_times.setImageResource(R.mipmap.icon_two_quicken_card);
                    } else if (item.getMultiple().intValue() == 3) {
                        quicken_times.setVisibility(View.VISIBLE);
                        quicken_times.setImageResource(R.mipmap.icon_three_quicken_card);
                    } else {
                        quicken_times.setVisibility(View.GONE);
                    }
                } else {
                    quicken_times.setVisibility(View.GONE);
                }

                if (item.getProvider().equals("perfection")) {
                    task.setText("完善资料");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_invite)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("conversion")) {
                    task.setText("能量兑换");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_energy_exchange)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("attention")) {
                    task.setText("关注好友");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_attention)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("share")) {
                    task.setText("分享任务");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_share)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("publish")) {
                    task.setText("发布任务");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_publish)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("look")) {
                    task.setText("浏览任务");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_watch)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("comment")) {
                    task.setText("评论任务");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_comment)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("like")) {
                    task.setText("点赞任务");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_praise)
                            .dontAnimate()
                            .into(img);
                } else if (item.getProvider().equals("content")) {
                    task.setText("优质内容奖励");
                    Glide.with(context)
                            .load(R.mipmap.icon_item_content)
                            .dontAnimate()
                            .into(img);
                }
            }
        };

        listview.setAdapter(quickAdapter);
        listview.setFocusable(false);

    }

    @Override
    protected void initData() {
        showDialog(context, null);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.MINE_ENERGY, null, Url.MINE_ENERGY, new Callback<EnergyTaskBean>() {
            @Override
            public void onSuccess(EnergyTaskBean energyTaskBean) {
                dismissDialog();
                if (energyTaskBean.getCode() == Contacts.SUCCESS) {
                    mEnergyTaskBean = energyTaskBean;
                    rule.setText("兑换比率 " + energyTaskBean.getEnergyRatio() + ":" + 1);
                    enery.setText(energyTaskBean.getEnergy() + "");
//                    money.setText("可兑换" + energyTaskBean.getEnergy() / energyTaskBean.getEnergyRatio() + "元");
                    money.setText("可兑换" + energyTaskBean.getMoney().stripTrailingZeros().toPlainString() + "元");
                } else {
                    showImageToas(energyTaskBean.getMsg());
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                dismissDialog();
            }
        });

        requestData();

    }

    private void requestData() {
        HttpParams params = new HttpParams();
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.MINE_ENERGY_DETAIL, params, Url.MINE_ENERGY_DETAIL, new Callback<MineEnergyList>() {
            @Override
            public void onSuccess(MineEnergyList mineEnergyList) {
                if (mineEnergyList.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        quickAdapter.addAll(mineEnergyList.getPage().getList());
                    } else {
                        quickAdapter.addAll(mineEnergyList.getPage().getList());
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (mineEnergyList.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = mineEnergyList.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = mineEnergyList.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (mineEnergyList.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(mineEnergyList.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }

    //    @Override
    @OnClick({R.id.exchange, R.id.right_tv})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.right_tv:
                startActivity(SignActivity.class);
                break;
            case R.id.exchange:
                if (mEnergyTaskBean != null) {
                    if ((mEnergyTaskBean.getEnergy() / mEnergyTaskBean.getEnergyRatio()) > 0) {
                        DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_energy_exchange);
                        LinearLayout dialog_energy_exchange = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
                        TextView title = dialog_energy_exchange.findViewById(R.id.title);
                        title.setText("能量值兑换");
                        TextView msg = dialog_energy_exchange.findViewById(R.id.msg);
                        msg.setText("您本次可兑换" + mEnergyTaskBean.getMoney().stripTrailingZeros().toPlainString() + "元（" + (mEnergyTaskBean.getMoney().multiply(new BigDecimal(mEnergyTaskBean.getEnergyRatio()))).stripTrailingZeros().toPlainString() + "）");
//                        msg.setText("您本次可兑换" + mEnergyTaskBean.getEnergy() / mEnergyTaskBean.getEnergyRatio() + "元（" + (mEnergyTaskBean.getEnergy() / mEnergyTaskBean.getEnergyRatio()) * mEnergyTaskBean.getEnergyRatio() + "）");
                        TextView msg_1 = dialog_energy_exchange.findViewById(R.id.msg_1);
                        msg_1.setText("是否确认兑换？");
                        TextView cancel = dialog_energy_exchange.findViewById(R.id.cancel);
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                DialogUtil.getInstance().dialog_center.dismiss();
                            }
                        });
                        TextView right_tv = dialog_energy_exchange.findViewById(R.id.right_tv);
                        right_tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Utils.isDoubleClick()) {
                                    return;
                                }
                                if ("确认兑换".equals(right_tv.getText().toString())) {
                                    showDialog(context, "兑换中...");
                                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.ENERGY_EXCHANGE, null, Url.ENERGY_EXCHANGE, new Callback<SendCodeBean>() {
                                        @Override
                                        public void onSuccess(SendCodeBean sendCodeBean) {
                                            dismissDialog();
                                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                EventBus.getDefault().post("refresh_mine");
                                                title.setText("兑换成功");
//                                                msg.setText((mEnergyTaskBean.getEnergy() / mEnergyTaskBean.getEnergyRatio()) * mEnergyTaskBean.getEnergyRatio() + "能量值兑换成功！");
                                                msg.setText((mEnergyTaskBean.getMoney().multiply(new BigDecimal(mEnergyTaskBean.getEnergyRatio()))).stripTrailingZeros().toPlainString() + "能量值兑换成功！");
                                                msg_1.setText("请到我的余额查看");
                                                right_tv.setText("查看余额");
                                                initData();
                                            } else {
                                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                } else {
                                                    showImageToas(sendCodeBean.getMsg());
                                                }
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            dismissDialog();
                                        }
                                    });
                                } else {
                                    DialogUtil.getInstance().dialog_center.dismiss();
                                    startActivity(MineWalletActivity.class);
                                }

                            }
                        });
                    } else {
                        showImageToas("能量值不足，请先去完成任务哦");
                    }
                }
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        requestData();
    }
}
